package com.ldc.common.views;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.ldc.common.R;
import com.ldc.common.common.CommonViewClick;
import com.ldc.common.utils.StringUtils;

public class StateView extends FrameLayout {
    private View viewLoading;
    private View viewNoData;

    private TextView tvName;
    private TextView tvRetry;

    private CommonViewClick<View> onTryViewClickListener;

    public StateView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }


    public void addOnRetryListener(CommonViewClick<View> click) {
        this.onTryViewClickListener = click;
    }

    private void initView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.layout_common_state_view, this);
        viewLoading = findViewById(R.id.view_loading);
        tvName = viewLoading.findViewById(R.id.tv_name);
    }


    public void showEmptyView() {
        ViewStub viewStub = findViewById(R.id.view_loading);
        if (viewStub != null) {
            viewNoData = viewStub.inflate();
            tvRetry = viewNoData.findViewById(R.id.tv_try);
            tvRetry.setOnClickListener(v -> {
                if (onTryViewClickListener != null) {
                    onTryViewClickListener.onRow(v);
                }
            });

        } else {
            viewNoData.setVisibility(View.VISIBLE);
        }
        hideLoading();

    }

    public void showLoadingView() {
        showLoadingView("数据加载中，请稍等");
    }

    public void showLoadingView(String message) {
        String info = message;
        if (StringUtils.isEmpty(message)) {
            info = "加载中，请稍等";
        }
        tvName.setText(info);
        if (viewLoading != null) {
            viewLoading.setVisibility(View.VISIBLE);
        }
        hideNoDate();
    }

    public void showContentView() {
        hideLoading();
        hideNoDate();
    }

    private void hideLoading() {
        if (viewLoading != null && viewLoading.getVisibility() == View.VISIBLE) {
            viewLoading.setVisibility(View.GONE);
        }
    }

    public void hideNoDate() {
        if (viewNoData != null && viewNoData.getVisibility() == View.VISIBLE) {
            viewNoData.setVisibility(View.GONE);
        }
    }


}
